import SwiftUI

struct FreeRecordingView: View {
    @EnvironmentObject var sensor: SensorRecorder
    @AppStorage("userName") private var userName: String = ""
    @Environment(\.dismiss) private var dismiss
    let mode: FreeRecordingMode
    
    // 录制状态
    @State private var isRecording: Bool = false
    @State private var isChewing: Bool = false
    @State private var elapsedTime: TimeInterval = 0
    
    // Session 数据
    @State private var session = FreeRecordingSession()
    @State private var currentSegmentStartDate: Date?
    @State private var currentSegmentStartIndex: Int = 0
    
    // UI 状态
    @State private var showNoteSheet: Bool = false
    @State private var noteText: String = ""
    @State private var showSaveButton: Bool = false
    
    // 上传状态
    @State private var isUploading: Bool = false
    @State private var uploadError: String?
    @State private var uploadSuccess: Bool = false
    
    // 定时器
    @State private var timer: Timer?
    
    var body: some View {
        ZStack {
            // 背景
            backgroundGradient
            
            ScrollView {
                VStack(spacing: 20) {
                    // 顶部标题
                    headerSection
                    
                    // 中间状态显示
                    statusSection
                        .padding(.vertical, 20)
                    
                    // 底部按钮
                    controlButtons
                }
                .padding(.bottom, 40)
            }
        }
        .navigationBarBackButtonHidden(isRecording)
        .onAppear {
            print("🔵 [FreeRecording] 页面出现")
            print("🔵 [FreeRecording] showNoteSheet: \(showNoteSheet)")
            print("🔵 [FreeRecording] showSaveButton: \(showSaveButton)")
            print("🔵 [FreeRecording] isRecording: \(isRecording)")
        }
        .sheet(isPresented: $showNoteSheet) {
            noteInputSheet
        }
        .overlay {
            if isUploading {
                uploadingOverlay
            }
        }
        .alert("上传失败", isPresented: .constant(uploadError != nil)) {
            Button("确定") {
                uploadError = nil
                // 失败后也不自动跳转，用户可以重试或点击取消按钮返回
            }
        } message: {
            Text(uploadError ?? "")
        }
        .alert("上传成功", isPresented: $uploadSuccess) {
            Button("确定") {
                uploadSuccess = false
                dismiss()
            }
        } message: {
            Text("数据已成功保存到服务器")
        }
    }
    
    // MARK: - UI Components
    
    private var backgroundGradient: some View {
        LinearGradient(
            colors: [.black.opacity(0.95), .purple.opacity(0.5), .pink.opacity(0.3)],
            startPoint: .topLeading,
            endPoint: .bottomTrailing
        )
        .ignoresSafeArea()
    }
    
    private var headerSection: some View {
        VStack(spacing: 6) {
            Image(systemName: "record.circle.fill")
                .font(.system(size: 40, weight: .bold))
                .foregroundStyle(LinearGradient(
                    colors: [.purple, .pink, .orange],
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                ))
            
            Text(mode == .nonChewingOnly ? "自由记录2" : "自由记录")
                .font(.system(.title2, design: .rounded).weight(.bold))
                .foregroundColor(.white)
            
            Text(mode == .nonChewingOnly ? "记录非咀嚼过程" : "记录完整用餐过程")
                .font(.system(.caption, design: .rounded))
                .foregroundColor(.white.opacity(0.7))
        }
        .padding(.top, 20)
    }
    
    private var statusSection: some View {
        VStack(spacing: 16) {
            // 时长显示
            VStack(spacing: 6) {
                Text("总时长")
                    .font(.system(.caption2, design: .rounded))
                    .foregroundColor(.white.opacity(0.7))
                Text(formatTime(elapsedTime))
                    .font(.system(size: 36, weight: .bold, design: .rounded))
                    .foregroundColor(.white)
            }
            
            // 实时传感器数据
            if isRecording {
                sensorDataDisplay
            }
            
            // 统计信息
            if isRecording {
                statisticsCards
            }
        }
    }
    
    private var sensorDataDisplay: some View {
        VStack(spacing: 10) {
            // 加速度计折线图
            RealtimeChartView(
                title: "加速度计",
                icon: "arrow.up.and.down.and.arrow.left.and.right",
                color: .cyan,
                xData: sensor.accXHistory,
                yData: sensor.accYHistory,
                zData: sensor.accZHistory
            )
            
            // 陀螺仪折线图
            RealtimeChartView(
                title: "陀螺仪",
                icon: "gyroscope",
                color: .orange,
                xData: sensor.gyroXHistory,
                yData: sensor.gyroYHistory,
                zData: sensor.gyroZHistory
            )
        }
    }
    
    private var statisticsCards: some View {
        HStack(spacing: 20) {
            StatCard(title: "咀嚼段", value: "\(session.chewingSegments.count)", color: .green)
            StatCard(title: "非咀嚼段", value: "\(session.nonChewingSegments.count)", color: .orange)
            StatCard(title: "样本数", value: "\(sensor.sampleCount)", color: .cyan)
        }
        .padding(.horizontal, 10)
    }
    
    private var controlButtons: some View {
        VStack(spacing: 12) {
            if !isRecording && !showSaveButton {
                // 开始按钮
                startButton
                cancelButton
            } else if showSaveButton {
                // 完成页面：烟花效果 + 统计信息 + 保存按钮
                completionView
            } else {
                // 录制中的按钮
                if mode == .normal {
                    toggleButton
                }
                finishButton
            }
        }
        .padding(.horizontal, 20)
    }
    
    private var completionView: some View {
        VStack(spacing: 20) {
            // 烟花庆祝效果
            ZStack {
                // 多个烟花粒子
                ForEach(0..<12, id: \.self) { index in
                    Circle()
                        .fill(fireworkColors[index % fireworkColors.count])
                        .frame(width: 8, height: 8)
                        .offset(fireworkOffset(for: index))
                        .opacity(showSaveButton ? 0 : 1)
                        .animation(.easeOut(duration: 1.5).delay(Double(index) * 0.05), value: showSaveButton)
                }
                
                // 中心成就图标
                Image(systemName: "checkmark.circle.fill")
                    .font(.system(size: 60, weight: .bold))
                    .foregroundStyle(
                        LinearGradient(
                            colors: [.green, .teal],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                    .scaleEffect(showSaveButton ? 1.0 : 0.5)
                    .animation(.spring(response: 0.6, dampingFraction: 0.6).delay(0.3), value: showSaveButton)
            }
            .frame(height: 100)
            
            // 成就文字
            VStack(spacing: 8) {
                Text("🎉 记录完成！")
                    .font(.system(.title2, design: .rounded).weight(.bold))
                    .foregroundColor(.white)
                
                Text("总时长 \(formatTime(session.totalDuration))")
                    .font(.system(.body, design: .rounded))
                    .foregroundColor(.white.opacity(0.8))
            }
            .opacity(showSaveButton ? 1 : 0)
            .animation(.easeIn(duration: 0.5).delay(0.5), value: showSaveButton)
            
            // 统计卡片
            HStack(spacing: 16) {
                CompletionStatCard(
                    icon: "fork.knife",
                    title: "咀嚼段",
                    value: "\(session.chewingSegments.count)",
                    color: .green
                )
                CompletionStatCard(
                    icon: "pause.circle",
                    title: "非咀嚼段",
                    value: "\(session.nonChewingSegments.count)",
                    color: .orange
                )
                CompletionStatCard(
                    icon: "waveform",
                    title: "样本数",
                    value: "\(sensor.sampleCount)",
                    color: .cyan
                )
            }
            .padding(.horizontal, 10)
            .opacity(showSaveButton ? 1 : 0)
            .animation(.easeIn(duration: 0.5).delay(0.7), value: showSaveButton)
            
            // 保存按钮
            VStack(spacing: 12) {
                Button(action: { showNoteSheet = true }) {
                    Label("保存记录", systemImage: "square.and.arrow.down.fill")
                        .font(.system(.title3, design: .rounded).weight(.semibold))
                        .foregroundColor(.white)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 18)
                        .background(LinearGradient(
                            colors: [.blue, .purple],
                            startPoint: .leading,
                            endPoint: .trailing
                        ))
                        .cornerRadius(16)
                }
                
                Button("取消") {
                    dismiss()
                }
                .font(.system(.body, design: .rounded))
                .foregroundColor(.white.opacity(0.7))
                
                Text("提示：首次上传需要授权网络权限")
                    .font(.system(.caption2, design: .rounded))
                    .foregroundColor(.orange)
            }
            .opacity(showSaveButton ? 1 : 0)
            .animation(.easeIn(duration: 0.5).delay(0.9), value: showSaveButton)
        }
    }
    
    private var fireworkColors: [Color] {
        [.red, .orange, .yellow, .green, .cyan, .blue, .purple, .pink]
    }
    
    private func fireworkOffset(for index: Int) -> CGSize {
        let angle = Double(index) * (360.0 / 12.0) * .pi / 180.0
        let radius: CGFloat = showSaveButton ? 0 : 60
        return CGSize(
            width: CGFloat(cos(angle)) * radius,
            height: CGFloat(sin(angle)) * radius
        )
    }
    
    private var startButton: some View {
        Button(action: startRecording) {
            Label(mode == .nonChewingOnly ? "开始记录" : "开始咀嚼", systemImage: "play.fill")
                .font(.system(.title3, design: .rounded).weight(.semibold))
                .foregroundColor(.white)
                .frame(maxWidth: .infinity)
                .padding(.vertical, 18)
                .background(LinearGradient(
                    colors: [.green, .teal],
                    startPoint: .leading,
                    endPoint: .trailing
                ))
                .cornerRadius(16)
        }
    }
    
    private var toggleButton: some View {
        Button(action: toggleChewing) {
            Label(isChewing ? "停止咀嚼" : "继续咀嚼", systemImage: isChewing ? "pause.fill" : "play.fill")
                .font(.system(.title3, design: .rounded).weight(.semibold))
                .foregroundColor(.white)
                .frame(maxWidth: .infinity)
                .padding(.vertical, 18)
                .background(LinearGradient(
                    colors: isChewing ? [.orange, .red] : [.green, .teal],
                    startPoint: .leading,
                    endPoint: .trailing
                ))
                .cornerRadius(16)
        }
    }
    
    private var finishButton: some View {
        Button(action: finishRecording) {
            Label("结束记录", systemImage: "stop.fill")
                .font(.system(.body, design: .rounded).weight(.semibold))
                .foregroundColor(.white)
                .frame(maxWidth: .infinity)
                .padding(.vertical, 14)
                .background(.red.opacity(0.8))
                .cornerRadius(16)
        }
    }
    
    private var saveButton: some View {
        VStack(spacing: 12) {
            Button(action: { showNoteSheet = true }) {
                Label("保存记录", systemImage: "square.and.arrow.down.fill")
                    .font(.system(.title3, design: .rounded).weight(.semibold))
                    .foregroundColor(.white)
                    .frame(maxWidth: .infinity)
                    .padding(.vertical, 18)
                    .background(LinearGradient(
                        colors: [.blue, .purple],
                        startPoint: .leading,
                        endPoint: .trailing
                    ))
                    .cornerRadius(16)
            }
            
            Text("提示：首次上传需要授权网络权限")
                .font(.system(.caption2, design: .rounded))
                .foregroundColor(.orange)
        }
    }
    
    private var cancelButton: some View {
        Button("取消") {
            dismiss()
        }
        .font(.system(.body, design: .rounded))
        .foregroundColor(.white.opacity(0.7))
    }
    
    private var noteInputSheet: some View {
        VStack(spacing: 20) {
            // 顶部拖动条
            Capsule()
                .fill(Color.white.opacity(0.3))
                .frame(width: 40, height: 5)
                .padding(.top, 12)
                .onAppear {
                    print("🟡 [FreeRecording] 备注弹窗出现")
                }
            
            // 标题
            VStack(spacing: 8) {
                Image(systemName: "note.text")
                    .font(.system(size: 40, weight: .semibold))
                    .foregroundStyle(
                        LinearGradient(
                            colors: [.blue, .purple],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                
                Text("记录备注")
                    .font(.system(.title3, design: .rounded).weight(.bold))
                    .foregroundColor(.white)
                
                Text("请输入吃的东西（必填）")
                    .font(.system(.footnote, design: .rounded))
                    .foregroundColor(.white.opacity(0.7))
            }
            
            // 输入框
            TextField("如：花生/苹果", text: $noteText)
                .textFieldStyle(.roundedBorder)
                .padding(.horizontal, 4)
            
            // 错误提示
            if noteText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
                HStack(spacing: 6) {
                    Image(systemName: "exclamationmark.circle.fill")
                        .foregroundColor(.orange)
                    Text("必须填写吃的东西才能保存")
                        .font(.system(.caption, design: .rounded))
                        .foregroundColor(.orange)
                }
            }
            
            // 按钮
            HStack(spacing: 12) {
                Button("取消") {
                    showNoteSheet = false
                }
                .buttonStyle(.bordered)
                .tint(.white)
                
                Button("保存") {
                    saveAndUpload()
                }
                .buttonStyle(.borderedProminent)
                .tint(LinearGradient(
                    colors: [.blue, .purple],
                    startPoint: .leading,
                    endPoint: .trailing
                ))
                .disabled(noteText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
            }
            .padding(.top, 8)
        }
        .padding(24)
        .frame(maxWidth: .infinity)
        .background(
            LinearGradient(
                colors: [
                    Color(red: 0.15, green: 0.15, blue: 0.2),
                    Color(red: 0.1, green: 0.1, blue: 0.15)
                ],
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
        )
        .cornerRadius(24)
        .presentationDetents([.height(320)])
        .presentationDragIndicator(.hidden)
    }
    
    private var uploadingOverlay: some View {
        ZStack {
            Color.black.opacity(0.5).ignoresSafeArea()
            VStack(spacing: 20) {
                ProgressView()
                    .scaleEffect(1.5)
                    .tint(.white)
                Text("正在上传数据...")
                    .font(.system(.body, design: .rounded).weight(.medium))
                    .foregroundColor(.white)
            }
            .padding(40)
            .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 20))
        }
    }
    
    // MARK: - Recording Logic
    
    private func startRecording() {
        print("▶️ [FreeRecording] 开始录制")
        
        isRecording = true
        isChewing = (mode == .normal)
        session = FreeRecordingSession()
        currentSegmentStartDate = Date()
        currentSegmentStartIndex = 0
        
        // 启动传感器
        sensor.start(rateHz: 50)
        
        // 启动计时器
        elapsedTime = 0
        timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in
            elapsedTime = Date().timeIntervalSince(session.startDate)
        }
    }
    
    private func toggleChewing() {
        print("🔄 [FreeRecording] 切换状态: \(isChewing ? "咀嚼" : "非咀嚼") -> \(isChewing ? "非咀嚼" : "咀嚼")")
        print("📊 [FreeRecording] 当前 sensor.rawSamples.count: \(sensor.rawSamples.count)")
        
        // 保存当前段
        saveCurrentSegment()
        
        // 切换状态
        isChewing.toggle()
        print("✅ [FreeRecording] 状态已切换为: \(isChewing ? "咀嚼" : "非咀嚼")")
        
        // 开始新段
        currentSegmentStartDate = Date()
        currentSegmentStartIndex = sensor.rawSamples.count
        print("🆕 [FreeRecording] 新段开始，startIndex: \(currentSegmentStartIndex)")
    }
    
    private func finishRecording() {
        print("⏹️ [FreeRecording] 结束录制，样本数: \(sensor.sampleCount)")
        print("📊 [FreeRecording] 当前状态: \(isChewing ? "咀嚼" : "非咀嚼"), sensor.rawSamples.count: \(sensor.rawSamples.count)")
        
        // 保存最后一段
        print("💾 [FreeRecording] 保存最后一段...")
        saveCurrentSegment()
        print("📊 [FreeRecording] 保存后，总段数: \(session.segments.count)")
        
        // 停止传感器和计时器
        sensor.stop()
        timer?.invalidate()
        timer = nil
        
        isRecording = false
        session.endDate = Date()
        
        // 只有有数据才显示保存按钮
        if sensor.sampleCount > 0 {
            showSaveButton = true
        } else {
            print("⚠️ [FreeRecording] 无数据，返回")
            dismiss()
        }
    }
    
    private func saveCurrentSegment() {
        guard let startDate = currentSegmentStartDate else {
            print("⚠️ [FreeRecording] currentSegmentStartDate 为 nil，跳过")
            return
        }
        
        let endDate = Date()
        let endIndex = sensor.rawSamples.count
        
        print("📐 [FreeRecording] 当前状态: \(isChewing ? "咀嚼" : "非咀嚼"), startIndex: \(currentSegmentStartIndex), endIndex: \(endIndex)")
        
        guard endIndex > currentSegmentStartIndex else {
            print("⚠️ [FreeRecording] 段数据为空（endIndex=\(endIndex), startIndex=\(currentSegmentStartIndex)），跳过")
            return
        }
        
        let rawSamples = Array(sensor.rawSamples[currentSegmentStartIndex..<endIndex])
        
        let segment = RecordingSegment(
            type: isChewing ? .chewing : .nonChewing,
            startDate: startDate,
            endDate: endDate,
            rawSamples: rawSamples
        )
        
        session.segments.append(segment)
        print("✅ [FreeRecording] 保存段: \(segment.type.rawValue), 样本数: \(rawSamples.count), 总段数: \(session.segments.count)")
    }
    
    private func saveAndUpload() {
        showNoteSheet = false
        session.note = noteText
        
        Task {
            await uploadDataToServer()
        }
    }
    
    // MARK: - Upload
    
    private func uploadDataToServer() async {
        await MainActor.run { isUploading = true }
        
        do {
            let timestamp = Int(Date().timeIntervalSince1970)
            
            // 非咀嚼专用模式：只上传一个完整文件
            if mode == .nonChewingOnly {
                print("📤 [FreeRecording] 非咀嚼模式：仅上传一个完整文件")
                let singleURL = try createCompleteCSVFromSegments(session.segments)
                let encodedUserName = userName.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? userName
                let objectKey = "chew_data/\(encodedUserName)/\(timestamp)_no_chewing_raw.csv"
                let singleOSSUrl = try await OSSUploadService.shared.uploadFile(fileURL: singleURL, objectKey: objectKey)
                
                let duration = session.totalDuration
                try await ChewDataService.shared.saveChewData(
                    scenario: "自由记录-非咀嚼",
                    note: noteText,
                    userName: userName,
                    duration: duration,
                    rawCsvUrl: singleOSSUrl,
                    timestamp: session.startDate,
                    sessionUUID: session.sessionUUID
                )
                
                await MainActor.run {
                    isUploading = false
                    uploadSuccess = true
                }
                return
            }
            
            print("📤 [FreeRecording] 开始上传，共 \(session.segments.count) 个段")
            for (i, seg) in session.segments.enumerated() {
                print("📑 [FreeRecording] 段 #\(i): \(seg.type.rawValue), 样本数: \(seg.rawSamples.count)")
            }
            
            // 上传每个段
            for (index, segment) in session.segments.enumerated() {
                // 创建 CSV 文件
                let rawURL = try createCSV(samples: segment.rawSamples, type: "raw", suffix: "\(segment.type.rawValue)_\(index)", typeLabel: segment.type.rawValue)
                print("📄 [FreeRecording] CSV 文件已创建: \(rawURL.lastPathComponent)")
                
                // 上传到 OSS (URL encode userName to handle spaces)
                let encodedUserName = userName.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? userName
                let rawKey = "chew_data/\(encodedUserName)/\(timestamp)_\(segment.type.rawValue)_\(index)_raw.csv"
                
                print("☁️ [FreeRecording] 上传到 OSS: \(rawKey)")
                let rawOSSUrl = try await OSSUploadService.shared.uploadFile(fileURL: rawURL, objectKey: rawKey)
                print("✅ [FreeRecording] Raw OSS URL: \(rawOSSUrl)")
                
                // 调用后端接口
                print("📡 [FreeRecording] 调用后端接口保存数据")
                try await ChewDataService.shared.saveChewData(
                    scenario: "自由记录-\(segment.type.rawValue)",
                    note: noteText,
                    userName: userName,
                    duration: segment.duration,
                    rawCsvUrl: rawOSSUrl,
                    timestamp: segment.startDate,
                    sessionUUID: session.sessionUUID
                )
                print("✅ [FreeRecording] 段 \(index+1) 保存成功")
            }
            
            // 上传完整文件（根据各段类型逐行写入 type）
            print("📤 [FreeRecording] 上传完整文件")
            let completeRawURL = try createCompleteCSVFromSegments(session.segments)
            
            let encodedUserName = userName.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? userName
            let completeRawKey = "chew_data/\(encodedUserName)/\(timestamp)_complete_raw.csv"
            
            let completeRawOSSUrl = try await OSSUploadService.shared.uploadFile(fileURL: completeRawURL, objectKey: completeRawKey)
            
            let totalDuration = session.segments.reduce(0) { $0 + $1.duration }
            try await ChewDataService.shared.saveChewData(
                scenario: "自由记录-complete",
                note: noteText,
                userName: userName,
                duration: totalDuration,
                rawCsvUrl: completeRawOSSUrl,
                timestamp: session.startDate,
                sessionUUID: session.sessionUUID
            )
            
            await MainActor.run {
                isUploading = false
                uploadSuccess = true
            }
            
        } catch {
            print("❌ [FreeRecording] 上传失败: \(error.localizedDescription)")
            
            let errorMessage = error.localizedDescription
            if errorMessage.contains("offline") || errorMessage.contains("network") {
                await MainActor.run {
                    isUploading = false
                    uploadError = "网络连接失败，请检查网络权限并重试"
                }
            } else {
                await MainActor.run {
                    isUploading = false
                    uploadError = error.localizedDescription
                }
            }
        }
    }
    
    private func createCompleteCSVFromSegments(_ segments: [RecordingSegment]) throws -> URL {
        let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let fileName = "\(userName)_complete_raw.csv"
        let fileURL = dir.appendingPathComponent(fileName)
        
        var s = "timestamp,ax,ay,az,wx,wy,wz,label\n"
        for seg in segments {
            let labelValue = (seg.type == .chewing) ? "1" : "0"
            for r in seg.rawSamples {
                s += String(format: "%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f", r.t, r.ax, r.ay, r.az, r.wx, r.wy, r.wz)
                s += ",\(labelValue)\n"
            }
        }
        try s.data(using: .utf8)?.write(to: fileURL, options: .atomic)
        return fileURL
    }
    
    private func createCSV(samples: [Any], type: String, suffix: String, typeLabel: String) throws -> URL {
        let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let fileName = "\(userName)_\(suffix)_\(type).csv"
        let fileURL = dir.appendingPathComponent(fileName)
        
        guard type == "raw", let rawSamples = samples as? [RawSample] else {
            throw NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid sample type"])
        }
        
        let csvContent = buildRawCSV(rawSamples, typeLabel: typeLabel)
        
        try csvContent.data(using: .utf8)?.write(to: fileURL, options: .atomic)
        return fileURL
    }
    
    private func buildRawCSV(_ samples: [RawSample], typeLabel: String) -> String {
        var s = "timestamp,ax,ay,az,wx,wy,wz,label\n"
        let normalized = typeLabel.replacingOccurrences(of: "-", with: "_").lowercased()
        let labelValue = (normalized == "chewing") ? "1" : "0"
        for r in samples {
            s += String(format: "%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f", r.t, r.ax, r.ay, r.az, r.wx, r.wy, r.wz)
            s += ",\(labelValue)\n"
        }
        return s
    }
    
    
    private func formatTime(_ time: TimeInterval) -> String {
        let minutes = Int(time) / 60
        let seconds = Int(time) % 60
        return String(format: "%02d:%02d", minutes, seconds)
    }
}

// MARK: - Supporting Views

private struct SensorRow: View {
    let title: String
    let icon: String
    let color: Color
    let x: Double
    let y: Double
    let z: Double
    
    var body: some View {
        VStack(spacing: 8) {
            HStack(spacing: 8) {
                Image(systemName: icon)
                    .font(.system(size: 14, weight: .semibold))
                    .foregroundColor(color)
                Text(title)
                    .font(.system(.caption, design: .rounded).weight(.semibold))
                    .foregroundColor(.white)
                Spacer()
            }
            
            HStack(spacing: 12) {
                AxisLabel(label: "X", value: x, color: .red)
                AxisLabel(label: "Y", value: y, color: .green)
                AxisLabel(label: "Z", value: z, color: .blue)
            }
        }
        .padding(12)
        .background(.white.opacity(0.1))
        .cornerRadius(12)
    }
}

private struct AxisLabel: View {
    let label: String
    let value: Double
    let color: Color
    
    var body: some View {
        VStack(spacing: 4) {
            Text(label)
                .font(.system(.caption2, design: .rounded).weight(.bold))
                .foregroundColor(color)
            Text(String(format: "%.3f", value))
                .font(.system(.caption, design: .monospaced).weight(.medium))
                .foregroundColor(.white)
        }
        .frame(maxWidth: .infinity)
    }
}

private struct StatCard: View {
    let title: String
    let value: String
    let color: Color
    
    var body: some View {
        VStack(spacing: 6) {
            Text(value)
                .font(.system(.title2, design: .rounded).weight(.bold))
                .foregroundColor(color)
            Text(title)
                .font(.system(.caption2, design: .rounded))
                .foregroundColor(.white.opacity(0.7))
        }
        .frame(maxWidth: .infinity)
        .padding(.vertical, 12)
        .background(.white.opacity(0.1))
        .cornerRadius(12)
    }
}

private struct CompletionStatCard: View {
    let icon: String
    let title: String
    let value: String
    let color: Color
    
    var body: some View {
        VStack(spacing: 8) {
            Image(systemName: icon)
                .font(.system(size: 24, weight: .semibold))
                .foregroundColor(color)
            
            Text(value)
                .font(.system(.title3, design: .rounded).weight(.bold))
                .foregroundColor(.white)
            
            Text(title)
                .font(.system(.caption, design: .rounded))
                .foregroundColor(.white.opacity(0.7))
        }
        .frame(maxWidth: .infinity)
        .padding(.vertical, 16)
        .background(
            RoundedRectangle(cornerRadius: 16)
                .fill(.white.opacity(0.1))
                .overlay(
                    RoundedRectangle(cornerRadius: 16)
                        .stroke(color.opacity(0.3), lineWidth: 1)
                )
        )
    }
}
